<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/04/03
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\goods;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use ImiApp\ApiServer\Api\Controller\Tpmecms;


use ImiApp\ApiServer\Api\Model\Goodscate;
use ImiApp\ApiServer\Api\Model\Goodsbrand;

use ImiApp\ApiServer\Api\Model\Goodssku;
use ImiApp\ApiServer\Api\Model\GoodsskuPrice;

use ImiApp\ApiServer\Api\Model\Goodsparam;
// @Auth(name="token",nologin={"*"})

/**
 * 商品公共接口👔
 * 
 * @Auth(name="token",nologin={"*"})
 * @Controller("/goods.com/")
 */
class Com extends Tpmecms
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取商品分类列表
     * @param int $level 等级
     * @param int $pid 上级id
     * @return void
     * @Action
     */
    public function get_goodscate($level = null, $pid = null)
    {


        $this->model = Goodscate::dbQuery();
        if ($level) {
            // $level = 0;
            $list = $this->model
                // ->with('children.children.children')
                ->where('level', '=', $level)->orderRaw('weigh desc, id asc')->select()->getArray();
        } elseif ($pid) {
            $list = $this->model->where('pid', '=', $pid)->orderRaw('weigh desc, id asc')->select()->getArray();
        } else {
            $list = $this->model
                // ->with('children.children.children')
                ->where('level', '=', 1)->orderRaw('weigh desc, id asc')->select()->getArray();
        }




        return $this->success('分类', $list);
    }




    /**
     * 获取商品分类下品牌列表
     *
     * @param string $goodscate_ids 商品分类ids
     * @return void
     * @Action
     */
    public function get_goodsbrand2($goodscate_ids = null)
    {

        if ($goodscate_ids) {
            // $this->modelcate = Goodscate::dbQuery();
            // $goodscate = $this->modelcate->whereIn('id', explode(',',$goodscate_ids))->column();
            // if (!$goodscate) {
            //     return $this->error('没有该商品分类');
            // }
            // if ($goodscate['level'] != 2) {
            //     return $this->error('请传递二级分类');
            // }

            $this->model = Goodsbrand::dbQuery();
            $list = $this->model->whereIn('goodscate_id', explode(',', $goodscate_ids))->where('status', '=', 'up')->orderRaw('goodscate_id desc,weigh desc, id asc')->select()->getArray();
        } else {
            $this->model = Goodsbrand::dbQuery();
            $list = $this->model->where('status', '=', 'up')->orderRaw('weigh desc, id asc')->select()->getArray();
        }

        return $this->success('品牌', $list);
    }


    /**
     * 获取商品分类下品牌列表
     *
     * @param int $goodscate_id 商品分类
     * @return void
     * @Action
     */
    public function get_goodsbrand($goodscate_id = null)
    {
        if ($goodscate_id) {
            $this->modelcate = Goodscate::dbQuery();
            $goodscate = $this->modelcate->where('id', '=', $goodscate_id)->find();
            if (!$goodscate) {
                return $this->error('没有该商品分类');
            }
            if ($goodscate['level'] != 2) {
                return $this->error('请传递二级分类');
            }

            $this->model = Goodsbrand::dbQuery();
            $list = $this->model->where('goodscate_id', '=', $goodscate_id)->where('status', '=', 'up')->orderRaw('weigh desc, id asc')->select()->getArray();
        } else {
            $this->model = Goodsbrand::dbQuery();
            $list = $this->model->where('status', '=', 'up')->orderRaw('weigh desc, id asc')->select()->getArray();
        }

        return $this->success('品牌', $list);
    }



    /**
     * 获取商品分类下参数列表
     *
     * @param int $goodscate_id 商品分类
     * @return void
     * @Action
     */
    public function get_goodsparam($goodscate_id = null)
    {
        if ($goodscate_id) {
            $this->modelparam = Goodscate::dbQuery();
            $goodscate = $this->modelparam->where('id', '=', $goodscate_id)->find();
            if (!$goodscate) {
                return $this->error('没有该商品分类');
            }
            if ($goodscate['level'] != 1) {
                return $this->error('请传递一级分类');
            }

            $this->model = Goodsparam::dbQuery();
            $list = $this->model->where('goodscate_id', '=', $goodscate_id)->orderRaw('weigh desc, id asc')->select()->getArray();
        }

        return $this->success('参数', $list);
    }





    /**
     * 商品列表👔
     *
     * @param integer $page 页1
     * @param integer $limit 数量10
     * @param string $search 搜索
     * @param string $type 商品类型:normal=实体商品,virtual=虚拟商品,service=服务
     * @param string $new_status 商品类型:new=全新,unused=闲置,soon=临期
     * @param string $status 商品状态:up=上架,hidden=隐藏商品,down=下架
     * @return void
     * @Action
     */
    public function goods_list(?int $page = 1, ?int $limit = 10, $search = null, $type = null, $status = null, $new_status = null, $params = null)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $where['apply_status'] = '2'; //通过审核
        if ($search)
            $where['title'] = ['like', '%' . $search . '%'];
        if ($type)
            $where['type'] = $type;
        if ($status)
            $where['status'] = $status;
        if ($new_status)
            $where['new_status'] = $new_status;
        // if($params)
        //     $where['params'] = $params;

        $list = Db::name('goods')
            // ->whereEx($this->whereCom)
            ->whereEx($where)
            ->orderRaw('createtime desc')
            ->whereIsNull('deletetime')
            ->page($page, $limit)
            ->select()->getArray();
        if ($list) {
            foreach ($list as $key => &$val) {
                $this->ChangGoodsField($val);
                $val['store'] = $this->getStoreData2($val['store_id']);
            }
        }
        return $this->success('', $list);
    }



    /**
     * 店铺商品列表👔
     *
     * @param integer $store_id 店铺id
     * @param integer $page 页1
     * @param integer $limit 数量10
     * @param string $search 搜索
     * @param string $type 商品类型:normal=实体商品,virtual=虚拟商品,service=服务
     * @param string $new_status 商品类型:new=全新,unused=闲置,soon=临期
     * 
     * @return void
     * @Action
     */
    public function store_goods_list(?int $store_id, ?int $page = 1, ?int $limit = 10, $search = null, $type = null, $new_status = null, $params = null)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        if (!$store_id)
            return $this->error('请传递店铺');

        $where['apply_status'] = '2'; //通过审核
        $where['store_id'] = $store_id;
        if ($search)
            $where['title'] = ['like', '%' . $search . '%'];
        if ($type)
            $where['type'] = $type;

        $where['status'] = 'up'; //$status 商品状态:up=上架,hidden=隐藏商品,down=下架
        if ($new_status)
            $where['new_status'] = $new_status;
        // if($params)
        //     $where['params'] = $params;

        $list = Db::name('goods')
            // ->whereEx($this->whereCom)
            ->whereEx($where)
            ->orderRaw('createtime desc')
            ->whereIsNull('deletetime')
            ->page($page, $limit)
            ->select()->getArray();
        if ($list) {
            foreach ($list as $key => &$val) {
                $this->ChangGoodsField($val);
            }
        }
        return $this->success('', $list);
    }



    /**
     * 首页商品列表👔
     *
     * @param integer $page 页1
     * @param integer $limit 数量10
     * @param string $search 搜索
     * @param string $type 商品类型:normal=实体商品,virtual=虚拟商品,service=服务
     * @param string $new_status 商品类型:new=全新,unused=闲置,soon=临期
     * @param string $status 商品状态:up=上架,hidden=隐藏商品,down=下架
     * @return void
     * @Action
     */
    public function index_goods_list(?int $page = 1, ?int $limit = 10, $search = null, $type = null, $status = null, $new_status = null, $params = null)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;


        // if ($search)
        //     $where['title|subtitle|content'] = ['like', '%' . $search . '%'];
        if ($type)
            $where['type'] = $type;

        $where['status'] = 'up';
        $where['apply_status'] = '2'; //通过审核
        // if ($new_status)
        //     $where['new_status'] = $new_status;
        // if($params)
        //     $where['params'] = $params;

        $list = Db::name('goods')
            // ->whereEx($this->whereCom)
            ->whereEx($where)
            ->orderRaw('createtime desc')
            ->whereIsNull('deletetime')
            ->page($page, $limit)
            ->select()->getArray();
        if ($list) {
            foreach ($list as $key => &$val) {
                $this->ChangGoodsField($val);
                $val['store'] = $this->getStoreData2($val['store_id']);
            }
        }
        return $this->success('', $list);
    }

    /**
     * 商品详情👔
     *
     * @param int $id 商品id
     * @return void
     * @Action
     */
    public function goods_detail($id)
    {
        $where['id'] = $id;
        $where['apply_status'] = '2';
        $goods = Db::name('goods')
            // ->whereEx($this->whereCom)
            ->whereEx($where)
            ->whereIsNull('deletetime')
            ->select()->get();
        if ($goods) {
            $goods = $this->ChangGoodsField($goods);
            $goods['store'] = $this->getStoreData3($goods['store_id']);
        }


        if ($this->auth->isLogin())
            $this->IncViews($id);
        return $this->success('goods', $goods);
    }

    /**
     * 获取商品评论
     *
     * @param integer|null $goods_id 商品id
     * @param integer|null $page 1 
     * @param integer|null $limit 10
     * @param string $images 带图片传1
     * @param integer|null $goods_sku_price_id 规格id 可不传
     * @return void
     * @Action
     */
    public function get_goods_comment(?int $goods_id,?int $page=1,?int $limit = 10,$images=null,?int $goods_sku_price_id=null) {
        
        $page = $page ?: 1;
        $limit = $limit ?: 10;

        $where['goods_id'] = $goods_id;
        $where['status'] = 'show';
        if($goods_sku_price_id){
            $where['goods_sku_price_id'] = $goods_sku_price_id;
        }

        $count = Db::name('goods_comment')->whereEx($where)->whereIsNull('deletetime')->count();
        var_dump($where,$images);
        if(!empty($images)){
            var_dump('image');
            $list = Db::name('goods_comment')->whereEx($where)->whereIsNull('deletetime')->whereIsNotNull('images')->page($page,$limit)->select()->getArray();
        }else{
            $list = Db::name('goods_comment')->whereEx($where)->whereIsNull('deletetime')->page($page,$limit)->select()->getArray();
        }
        // var_dump($list);
        if($list){
            foreach ($list as $key => &$val) {
               $val['user'] = $this->GetUserData1($val['user_id']);
               unset($val['user_id']);
               $val['date'] = $this->TimeToStr($val['createtime']);
            }
        }

       return $this->success($count, $list);
    }



    /**
     * 获取商品评论详情
     *
     * @param integer|null $id 评论id
     * @return void
     * @Action
     */
    public function get_goods_comment_data(?int $id=null) {
        $where['id'] = $id;
        $where['status'] = 'show';

        $val = Db::name('goods_comment')->whereEx($where)->whereIsNull('deletetime')->find();
        if(!$val){
           return $this->error('没有该评论');
        }
        $val['user'] = $this->GetUserData1($val['user_id']);
        unset($val['user_id']);
        $val['date'] = $this->TimeToStr($val['createtime']);
        
        return $this->success($id, $val);
    }



    protected function ChangGoodsField($goods)
    {
        unset($goods['refuse_ps']);

        if ($goods['is_sku']) {
            $skuList = Goodssku::dbQuery()->whereEx(['pid' => 0, 'goods_id' => $goods['id']])->select()->getArray();
            if ($skuList) {
                foreach ($skuList as &$s) {
                    $s['children'] = Goodssku::dbQuery()->whereEx(['pid' => $s['id'], 'goods_id' => $goods['id']])->select()->getArray();
                }
            }
            $goods['skuList'] = $skuList;

            $skuPrice = GoodsskuPrice::dbQuery()->whereEx(['goods_id' => $goods['id']])->select()->getArray();
            $goods['skuPrice'] = $skuPrice;
        } else {
            // 将单规格的部分数据直接放到 goods 上
            $goodsSkuPrice = GoodsskuPrice::dbQuery()->where('goods_id', '=', $goods['id'])->order('id', 'asc')->find();

            $goods['stock'] = $goodsSkuPrice['stock'] ?? 0;
            $goods['sn'] = $goodsSkuPrice['sn'] ?? "";
            $goods['weight'] = $goodsSkuPrice['weight'] ?? 0;
            $goods['stock_warning'] = $goodsSkuPrice['stock_warning'];

            $goods['skuList'] = [];
            $goods['skuPrice'] = $goodsSkuPrice;
        }
        $goods['goodsbrand'] =  Db::name('goodsbrand')
            ->where('id', '=', $goods['goodsbrand_id'])
            // ->cache($this->db_cache_set)
            ->value('name');
        if ($goods['expire_time'] > 0) {
            $goods['expire_date'] = date('Y-m-d', $goods['expire_time']);
        }

        if ($this->auth->isLogin())
            $goods['likes'] = $this->IsLikesGoods($goods['id'], null, $this->auth->user()->id); //3商品
        return $goods;
    }


    /**
     * 获取商品最新logid
     *
     * @param int $goods_id 商品id
     * @return void
     * @Action
     */
    public function get_goodslog_id(int $goods_id)
    {

        return $this->success($goods_id, $this->getNewGoodslogId($goods_id));
    }

    /**
     * 添加显示记录
     *
     * @param [type] $id
     * @return void
     */
    protected function IncViews($id)
    {
        Db::name('goods')->where('id', '=', $id)->setFieldInc('views')->update();
        $this->AddViewlog(GOODS, $id, $this->auth->user()->id); //添加浏览记录
    }
}
